package com.icloud.gateway.authorization;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.icloud.common.core.constant.AuthConstant;
import com.icloud.common.web.domain.UserDto;
import com.icloud.gateway.config.IgnoreUrlsConfig;
import com.nimbusds.jose.JWSObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.text.ParseException;
import java.util.List;

/**
 * 鉴权管理器，用于判断是否有资源的访问权限
 * Created by im on 2020/6/19.
 */
@Slf4j
@Component
public class AuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        ServerHttpRequest request = authorizationContext.getExchange().getRequest();
        URI uri = request.getURI();
        PathMatcher pathMatcher = new AntPathMatcher();
        //白名单路径直接放行
        List<String> ignoreUrls = ignoreUrlsConfig.getUrls();
        for (String ignoreUrl : ignoreUrls) {
            if (pathMatcher.match(ignoreUrl, uri.getPath())) {
                return Mono.just(new AuthorizationDecision(true));
            }
        }
        //对应跨域的预检请求直接放行
        if (request.getMethod() == HttpMethod.OPTIONS) {
            return Mono.just(new AuthorizationDecision(true));
        }
        //内部接口（internal），禁止任何来源经过网关
        if (pathMatcher.match("/**" + AuthConstant.INTERNAL_URL_PATTERN, uri.getPath())) {
            return Mono.just(new AuthorizationDecision(false));
        }
        //不同用户体系登录不允许互相访问
        try {
            //从token中解析出用户信息
            String token = request.getHeaders().getFirst(AuthConstant.JWT_TOKEN_HEADER);
            if (StrUtil.isEmpty(token)) {
                return Mono.just(new AuthorizationDecision(false));
            }
            String realToken = token.replace(AuthConstant.JWT_TOKEN_PREFIX, "");
            JWSObject jwsObject = JWSObject.parse(realToken);
            String userStr = jwsObject.getPayload().toString();
            UserDto userDto = JSONUtil.toBean(userStr, UserDto.class);
            //后台账号不能访问非后台接口
            if (AuthConstant.ADMIN_CLIENT_ID.equals(userDto.getClientId())) {
                if (!pathMatcher.match(AuthConstant.ADMIN_URL_PATTERN, uri.getPath())) {
                    return Mono.just(new AuthorizationDecision(false));
                }
            }
            //app用户只能访问app接口
            if (AuthConstant.APP_CLIENT_ID.equals(userDto.getClientId())) {
                if (!pathMatcher.match(AuthConstant.APP_URL_PATTERN, uri.getPath())) {
                    return Mono.just(new AuthorizationDecision(false));
                }
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return Mono.just(new AuthorizationDecision(false));
        }
        //权限检测这里不做，用自定义注解实现
        return Mono.just(new AuthorizationDecision(true));
    }
}
